#include <iostream>
#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <cstdlib>
using namespace std;
map<string, string> entity2id, relation2id;

void readEntity2id() {
	ifstream inputfile("entity2id.txt");

	if (!inputfile) {
		cout << "Unable to open entity2id";
		exit(1);
	}

	string readinline;

	while (getline(inputfile, readinline)) {
		istringstream strstream;
		strstream.str(readinline);
		string entity;
		string id;
		strstream >> entity >> id;
		cout << "e:" << entity << " id: " << id << endl;
		//entity2id[id] = entity;
		entity2id[id] = entity;
	}
//	map<string,string>::iterator iter;
//	iter = entity2id.begin();
//	while(iter!=entity2id.end()){
//		cout<<iter->first<<" "<<iter->second<<endl;
//		iter++;
//	}
}

void readRelation2id() {
	ifstream inputfile("relation2id.txt");

	if (!inputfile) {
		cout << "Unable to open relation2id";
		exit(1);
	}

	string readinline;

	while (getline(inputfile, readinline)) {
		istringstream strstream;
		strstream.str(readinline);
		string relation;
		string id;
		strstream >> relation >> id;
		relation2id[id] = relation;
		cout << "r:" << relation << " id: " << id << endl;
	}
}

void transTrainData() {
	ifstream inputfile("valid2id.txt");

	if (!inputfile) {
		cout << "Unable to open train";
		exit(1);
	}

	string readinline;

	cout << "write train data starts()" << endl;
	ofstream outfile("valid.txt");

	if (!outfile) {
		cout << "cannot open outfile";
		exit(1);
	}

	while (getline(inputfile, readinline)) {
		istringstream strstream;
		strstream.str(readinline);
		cout << "line: " << readinline << endl;
		string s;
		string p;
		string o;
		strstream >> s >> o >> p;
		cout << "s:" << s << "o:" << o << "p:" << p << endl;
		if (entity2id.count(s) == 0)
			cout << s << " miss sub" << endl;
		if (relation2id.count(p) == 0)
			cout << p << " miss pre" << endl;
		if (entity2id.count(o) == 0)
			cout << o << " miss obj" << endl;
		outfile << entity2id[s] << '\t' << entity2id[o] << '\t' << relation2id[p] << endl;
	}
}

int main() {
	readEntity2id();
	readRelation2id();
	transTrainData();

	cout << "SUCCESS!!!" << endl;
	return 0;
}


